package utils;

import com.alibaba.fastjson.JSON;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Site;
import us.codecraft.webmagic.Spider;
import us.codecraft.webmagic.processor.PageProcessor;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * Created by zhituliu on 2016/4/14.
 */
public class AutoHomeSpider implements PageProcessor {

    private Site site = Site.me().setRetryTimes(3).setSleepTime(100).setTimeOut(3000).setUserAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0");

    static int count = 0;

    @Override
    public void process(Page page) {
        List links = page.getHtml().xpath("div[@class=\"article-wrapper\"]").links().regex("(http://www.autohome.com.cn/news/\\w+/\\w+.html)").all();
        page.addTargetRequests(links);
        if(count>0) {
            String title = page.getHtml().xpath("//h1//text()").toString();
            page.putField("title", title);
           // System.out.println("## "+title);
//            page.putField("number", page.getHtml().xpath("//i[@id=\"number\"]//text()"));
//            String time = page.getHtml().xpath("//time[@class=\"date updated\"]/text()").toString();
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//            try {
//                page.putField("time", String.valueOf(sdf.parse(time).getTime()).substring(0,10));
//            } catch (ParseException e) {
//                e.printStackTrace();
//            }
//            String content = page.getHtml().xpath("//div[@class=\"article-entry phpxs_content 20160112\"]").toString();
//            page.putField("url", page.getUrl().toString());
//            page.putField("intro", intro.replaceAll("\n","").replaceAll("\t","").replaceAll("\\s","").replaceAll("\r","").trim());
//            page.putField("content", content.replaceAll("uploads","zb_users/upload"));
//            List<String> listProcess = page.getHtml().xpath("//div[@class=\"article-entry phpxs_content 20160112\"]//img/@src").all();
//            page.putField("imgs", listProcess);
//            System.out.println(page.getUrl().toString());
//            System.out.println(JSON.toJSON(listProcess));
        }
        count++;
        System.out.println(count);
    }

    @Override
    public Site getSite() {
        return this.site;
    }

    public static void main(String[] ags) throws ParseException {//.addPipeline(new DataFilePipeline())
        for(int i=1;i<=2;i++) {
            Spider.create(new AutoHomeSpider()).addUrl("http://www.autohome.com.cn/news/" + i + "/").thread(5).run();
        }
    }
}
